package com.gostudy.gulimall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gostudy.common.utils.PageUtils;
import com.gostudy.common.utils.Query;

import com.gostudy.gulimall.product.dao.CategoryDao;
import com.gostudy.gulimall.product.entity.CategoryEntity;
import com.gostudy.gulimall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /*
   查询出所有的分类以树形结构组装起来
    */
    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查询出所有的列表
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        List<CategoryEntity> finalNode = new ArrayList<>();

        for (CategoryEntity entity : entityList) {
            if (entity.getParentCid() == 0) {
                finalNode.add(entity);
                entity.setCatLevel(1);
                entity.setChildren(selectChildrenList(entity,entityList));
            }
        }
        return finalNode;
    }

    //根据id删除当前菜单，删除之前先检查当前菜单是否被其他的地方引用了
    @Override
    public void removeMenusByIds(List<Long> asList) {

        // TODO: 2021/4/5 删除菜单前进行检查当前菜单是否被引用

        baseMapper.deleteBatchIds(asList);
    }

    public static List<CategoryEntity> selectChildrenList(CategoryEntity entity,List<CategoryEntity> entityList) {
        //将子菜单进行初始话操作
        List<CategoryEntity> childList = new ArrayList<>();
        entity.setChildren(new ArrayList<>());

        //从所有的分类中找出一级分类的子类
        for (CategoryEntity categoryEntity : entityList) {
            if (categoryEntity.getParentCid().equals(entity.getCatId())) {
                categoryEntity.setCatLevel(entity.getCatLevel() + 1);
                childList.add(categoryEntity);
                categoryEntity.setChildren(selectChildrenList(categoryEntity, entityList));
            }

        }
        return childList;
    }

}